package bookstore.servlet;

import bookstore.bound.order.OrderDisp;
import bookstore.bound.order.RecipientForm;
import bookstore.bound.order.ShoppingCart;
import bookstore.manager.AuthManager;
import bookstore.manager.BookManager;
import bookstore.manager.OrderManager;
import bookstore.manager.UserManager;
import bookstore.model.Order;
import bookstore.model.UserProfile;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/api/custom")
public class CustomServlet {
    protected AuthManager authManager;
    protected UserManager userManager;
    protected BookManager bookManager;
    protected OrderManager orderManager;

    public CustomServlet(AuthManager authManager, UserManager userManager, BookManager bookManager, OrderManager orderManager) {
        System.out.println(String.format("Constructor of %s", this.getClass().getName()));
        this.authManager = authManager;
        this.userManager = userManager;
        this.bookManager = bookManager;
        this.orderManager = orderManager;
    }

    @PostMapping("/cart")
    public Order postCart(HttpSession session, @RequestBody ShoppingCart shoppingCart, BindingResult errors) {
        authManager.requireLogin(session);
        errors.hasErrors();
        return orderManager.generateOrder(session, shoppingCart);
    }

    @PostMapping("/order")
    public Map postOrder(HttpSession session, @RequestBody RecipientForm recipientForm, BindingResult errors) {
        authManager.requireLogin(session);
        errors.hasErrors();
        return orderManager.submitOrder(session, recipientForm);
    }

    @GetMapping("/order")
    public Set<OrderDisp> getOrders(HttpSession session) {
        authManager.requireLogin(session);
        return orderManager.getUserOrders(session);
    }

    @GetMapping("/profile")
    public Map getProfile(HttpSession session) {
        authManager.requireLogin(session);
        return userManager.getUserProfile(session);
    }

    @PostMapping("/profile")
    public Map postProfile(HttpSession session, @RequestBody Map request) throws IOException {

        System.out.println(request);
//        authManager.requireLogin(session);
        Integer uid = (Integer) request.get("userid");
        UserProfile userProfile = new UserProfile(uid.longValue());
        userProfile.setAvatar((String) request.get("avatar"));
        userProfile.setFavBook((String) request.get("favBook"));
        userProfile.setGender((String) request.get("gender"));

        return userManager.updateProfile(session, userProfile);
    }

}
